<?PHP

/**
 * OP_FeaturetteTabsWidget
 *
 * @package OnePress Theme
 * @author Sean Sullivan
 **/

class OP_FeaturetteTabsWidget extends OP_WidgetTemplate{
	function render(){
		$title = strlen($this->values['title']) > 0 ? $this->values['title'] : 'Featured Posts';
		$feature_content = array();
		
		$count = 0;
		foreach($this->values['tabs'] as $tab){
			
			/**
			 * get_posts() does not support a mixed query with tag and category...
			 */
			if($tab['type'] == 'category'){
				$features_temp = get_posts('category='.$tab['id'].'&orderby=date');
				$features = array();
				foreach($features_temp as $feature){
					$tags = get_the_terms($feature->ID, 'post_tag');
					if($tags && count($tags) > 0){
						foreach($tags as $tag){
							if($tag->name == 'featurette'){
								$features[] = $feature;
								break;
							}
						}
					}
				}
			}
			else{
				$args = array(
					'tag'		=>	'featurette '.$tab['slug'],
					'orderby'	=>	'date'
				);
				$features = get_posts($args);
			}
			
			global $post;
			global $OnePress;
			
			// Get available features 
			$features = $OnePress->feature_registry->get_available($features);
			
			if(count($features) > 0){
				$content = array();
				for($i = 0; $i < min($tab['columns'],count($features)); $i++){
					$link = get_permalink($features[$i]->ID); // Get link to post

					// Look for excerpt, if not one, create one from beginning of post
					if($features[$i]->post_excerpt){
						$post = $features[$i]->post_excerpt;
					}
					else{
						$post = $features[$i]->post_content;
						// strip_tags when creating excerpt because we don't want to include <img> tags, etc
						$post = strlen($post) > 200 ? substr(strip_tags($post),0,200).'...' : strip_tags($post);
					}
				
					$img = ''; // default image here
					$imgsize = $tab['columns'] == 1 || count($features) == 1 ? 'featurette' : 'thumbnail';
					// Check custom fields for images
				
					$img = OP_ImageSelection::get_image($features[$i]->ID,$imgsize);

					$tab_classes = array('oneup','twoup','threeup','fourup','fiveup','sixup','sevenup');
					$content[] = array(
						'class' 	=> $tab_classes[(min($tab['columns'],count($features)) -1)],
						'quantity'	=> min($tab['columns'],count($features)),
						'title'		=> $features[$i]->post_title,
						'link' 		=> $link,
						'image'		=> $img,
						'excerpt'	=> $post,
						'all'		=> $features[$i]
					);
				}
				
				// Assign tab name
				$feature_content[$count]['name'] = ucwords($tab['name']);
				
				// Add feature content to tab
				$feature_content[$count]['content'] = $content;
				
				$count++; // Only increase count if we have added a tab
			} // END if(count($features) > 0)
			
		}
		
		include(TEMPLATEPATH.'/widgets/template.featurette_tabs.php'); // Include widget template file
	}
	
	function get_tags(){
		global $wpdb;
		
		/**
		 * Get results of all tags from posts that are also tagged with 'featurette'
		 * TODO - optimize this query, currently using temp...
		**/
		$sql = "SELECT DISTINCT t.term_id as id, t.slug, t.name, tt.taxonomy as type
			FROM $wpdb->term_taxonomy tt
			LEFT JOIN ($wpdb->term_relationships tr, $wpdb->terms t)
			ON (tr.term_taxonomy_id=tt.term_taxonomy_id AND tt.term_id=t.term_id)
			WHERE tr.object_id
			IN (
				SELECT tr.object_id
				FROM $wpdb->term_taxonomy tt
       			LEFT JOIN ($wpdb->term_relationships tr, $wpdb->terms t)
  				ON (tr.term_taxonomy_id=tt.term_taxonomy_id AND tt.term_id=t.term_id)
				WHERE t.name='featurette'
			) AND (tt.taxonomy = 'post_tag' OR tt.taxonomy = 'category') ORDER BY t.name";

		$result = $wpdb->get_results($sql);
		$this->tags = array();
		foreach($result as $tag){
			if(in_array($tag->name,array('feature','featurette'))) continue; // filter these out, we don't want them to show up in our widget options
			$this->tags[$tag->id] = array('name'=>$tag->name,'slug'=>$tag->slug,'type'=>$tag->type);
		}
	}
	
	function do_post($post){
		$this->get_tags();

		$tabs = array();
		for($i = 0; $i < count($post['tab']['tag']); $i++){
			if($post['tab']['tag'][$i] == '') continue;
			
			$tabs[] = array(
				'id'		=>	attribute_escape($post['tab']['tag'][$i]),
				'slug'		=> attribute_escape($this->tags[$post['tab']['tag'][$i]]['slug']),
				'name'		=> attribute_escape($this->tags[$post['tab']['tag'][$i]]['name']),
				'type'		=> attribute_escape($this->tags[$post['tab']['tag'][$i]]['type']),
				'columns'	=>	attribute_escape($post['tab']['columns'][$i])
			);
		}
		
		$title = attribute_escape($post['title']);
		return array('tabs'=>$tabs,'title'=>$title);
	}
	
	function options(){
		if(!isset($this->tags)) $this->get_tags();
		
		echo '<p>';
		echo '<p><label for="widget_op_featurette_tabs-title-'.$this->values['number'].'">'._e('Title:').' <input class="widefat" id="widget_op_featurette_tabs-title-'.$this->values['number'].'" name="widget_op_featurette_tabs['.$this->values['number'].'][title]" type="text" value="'.$this->values['title'].'" /></label></p>';
		if(count($this->tags)>0){
			echo '<div><a href="#" class="op_add_tab_trigger">+ Add Tab</a></div>',
				'<div class="tab_options" style="display:none">',
				'<a href="#" class="op_remove_tab_trigger">X</a>',
				'<label>Select tag: </label><select name="widget_op_featurette_tabs['.$this->values['number'].'][tab][tag][]">',
				'<option></option>';

			foreach($this->tags as $id => $values){
				echo '<option value="'.$id.'">'.$values['name'].'</option>';
			}

			echo '</select>',
				'<span class="columns_label">Posts in tab: </span>',
				'<input type="text" name="widget_op_featurette_tabs['.$this->values['number'].'][tab][columns][]" value="1"/>',
				'</div>';
		}
		else echo '<div>You have not yet tagged any posts "featurette".</div>';
		
		echo '<div class="op_current_tabs">';
		if(count($this->values['tabs'])>0){
			foreach($this->values['tabs'] as $tab){
				echo '<div class="tab_options">',
					'<a href="#" class="op_remove_tab_trigger">X</a>',
					'<label>Select tag: </label><select name="widget_op_featurette_tabs['.$this->values['number'].'][tab][tag][]">',
					'<option></option>';
					
				foreach($this->tags as $id => $values){
					$checked = $tab['id'] == $id ? ' SELECTED' : '';
					echo '<option value="'.$id.'"'.$checked.'>'.$values['name'].'</option>';
				}
				echo '</select>',
					'<span class="columns_label">Posts in tab: </span>',
					'<input type="text" name="widget_op_featurette_tabs['.$this->values['number'].'][tab][columns][]" value="'.$tab['columns'].'"/>',
					'</div>';			
			}	
		}
		
		echo '</div>',
			'</p>';

	}
	
	/**
	 * Add styles and javascript for rendered widget
	 *
	 * @return void
	 * @author Sean
	 **/
	function head(){
		$url = get_bloginfo('template_directory').'/';
		wp_register_script('opfeaturettetabsjs', $url.'scripts/featurette_tabs.js',array('onepressjs'));
		wp_enqueue_script('opfeaturettetabsjs');
	}
	
	/**
	 * Add styles and javascript for widget admin
	 *
	 * @return void
	 * @author Sean
	 **/
	function admin_head(){
		$url = get_bloginfo('template_directory').'/op/admin/';
		wp_register_script('opfeaturettetabsadminjs', $url.'scripts/featurette_tabs.js',array('jquery','jquery-ui-sortable'));
		wp_enqueue_script('opfeaturettetabsadminjs');
		wp_register_style('opfeaturettetabsadmin',$url.'styles/featurette_tabs.css');
		wp_enqueue_style('opfeaturettetabsadmin');
	}
}

$widget = new OP_Widget('featurette_tabs');
$widget->setMeta('OP Featurette Tabs','Show featurette posts in tabs');
$widget->setDefaults(array('title'=>''));
$widget->setAdminDimensions(415,350);

$opw_featurette_tabs = new OP_FeaturetteTabsWidget($widget);
add_action('widgets_init', array($opw_featurette_tabs, 'init'));
?>